<script setup>
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

// Router instance
const router = useRouter()

// Form data matching C# model field names exactly
const formData = reactive({
  EarSignal: '',
  Variety: null,
  ElectronicEarTag: '',
  GeneRank: null,
  FatherNumber: null,
  MotherNumber: null,
  Gender: null,
  BirthStatus: null,
  DateofBirth: null,
  EntryDate: null,
  PlaceOfBirth: null,
  BirthWeight: null,
  Note: ''
})

// Dropdown options
const fatherNumberOptions = [
  { value: 1, label: '父耳号-001' },
  { value: 2, label: '父耳号-002' },
  { value: 3, label: '父耳号-003' },
  { value: 4, label: '父耳号-004' },
  { value: 5, label: '父耳号-005' }
]

const motherNumberOptions = [
  { value: 1, label: '母耳号-001' },
  { value: 2, label: '母耳号-002' },
  { value: 3, label: '母耳号-003' },
  { value: 4, label: '母耳号-004' },
  { value: 5, label: '母耳号-005' }
]

const genderOptions = [
  { value: 1, label: '公' },
  { value: 2, label: '母' }
]

const birthStatusOptions = [
  { value: 1, label: '单胎' },
  { value: 2, label: '双胎' },
  { value: 3, label: '三胎' },
  { value: 4, label: '四胎' },
  { value: 5, label: '五胎' },
  { value: 6, label: '六胎' }
]

const placeOfBirthOptions = [
  { value: 1, label: '场地A' },
  { value: 2, label: '场地B' },
  { value: 3, label: '场地C' },
  { value: 4, label: '场地D' }
]

// Validation state
const validationErrors = reactive({
  EarSignal: false,
  Variety: false,
  ElectronicEarTag: false,
  GeneRank: false,
  FatherNumber: false,
  MotherNumber: false,
  Gender: false,
  BirthStatus: false,
  DateofBirth: false,
  EntryDate: false,
  PlaceOfBirth: false,
  BirthWeight: false,
  Note: false
})

// Validation functions
const validateField = (field) => {
  if (field === 'Note') {
    validationErrors[field] = false // Note is optional
    return
  }
  
  const value = formData[field]
  if (value === null || value === undefined || value === '') {
    validationErrors[field] = true
  } else if (typeof value === 'string' && value.trim() === '') {
    validationErrors[field] = true
  } else {
    validationErrors[field] = false
  }
}

const validateForm = () => {
  let isValid = true
  Object.keys(formData).forEach(key => {
    if (key !== 'Note') { // Note is optional
      validateField(key)
      if (validationErrors[key]) {
        isValid = false
      }
    }
  })
  return isValid
}

// Action handlers
const handleAdd = () => {
  // Reset form
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  Object.keys(validationErrors).forEach(key => {
    validationErrors[key] = false
  })
  console.log('新增记录')
}

const handleSave = async () => {
  // Step 1: Validate form before any API calls
  if (!validateForm()) {
    // Collect all missing fields for user feedback
    const missingFields = []
    const fieldNames = {
      EarSignal: '耳号',
      Variety: '品种',
      ElectronicEarTag: '电子耳标号',
      GeneRank: '基因等级',
      FatherNumber: '父耳号',
      MotherNumber: '母耳号',
      Gender: '性别',
      BirthStatus: '出生状态',
      DateofBirth: '出生日期',
      EntryDate: '入场日期',
      PlaceOfBirth: '出生场地',
      BirthWeight: '出生重量'
    }
    
    for (const [field, name] of Object.entries(fieldNames)) {
      if (validationErrors[field]) {
        missingFields.push(name)
      }
    }
    
    // Show comprehensive warning to user
    const message = `请填写以下必填项目：\n\n${missingFields.join('\n')}\n\n请检查标有红色星号(*)的字段。`
    alert(message)
    
    console.warn('表单验证失败，请检查必填字段:', missingFields)
    return // Stop execution if validation fails
  }
  
  // Step 2: Form is valid, prepare data for API
  console.log('表单验证通过，准备保存 livestock record:', formData)
  
  try {
    // Step 3: Make API call with proper error handling
    const response = await Writes.post('/Management/CreatedEweFile', formData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('API Response:', response)
    
    // Step 4: Handle API response
    if (response.data && response.data.code === 100) {
      alert('新增成功！')
      router.push('/livestock-list')
      // Optional: Reset form after successful save
      // handleAdd()
    } else {
      // Handle API success but business logic failure
      const errorMsg = response.data?.message || '服务器返回错误，请稍后重试'
      alert(`保存失败：${errorMsg}`)
      console.error('API业务逻辑错误:', response.data)
    }
    
  } catch (error) {
    // Step 5: Handle network/API errors
    console.error('API调用失败:', error)
    
    let errormessage = '网络错误或服务器异常，请检查网络连接后重试'
    
    if (error.response) {
      // Server responded with error status
      errormessage = error.response.data?.message || `服务器错误 (${error.response.status})`
    } else if (error.request) {
      // Request made but no response received
      errormessage = '无法连接到服务器，请检查服务器是否运行'
    }
    
    alert(`保存失败：${errormessage}`)
  }
}

const handleUndo = () => {
  console.log('撤销操作')
  // Implement undo logic here
}

const handleDelete = () => {
  if (confirm('确定要删除这条记录吗？')) {
    console.log('删除记录')
    // Implement delete logic here
  }
}

const navigateToList = () => {
  router.push('/livestock-list')
}
</script>

<template>
  <div class="livestock-management">
    <!-- Top Action Buttons -->
    <div class="action-buttons">
      <button class="btn btn-red" @click="handleAdd">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
        </svg>
        新增
      </button>
      <button class="btn btn-red" @click="handleSave">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/>
        </svg>
        保存
      </button>
      <button class="btn btn-red" @click="handleUndo">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/>
        </svg>
        撤销
      </button>
      <button class="btn btn-red" @click="handleDelete">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
        </svg>
        删除
      </button>
      <button class="btn btn-red" @click="navigateToList">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
        </svg>
        列表
      </button>
    </div>

    <!-- Basic Information Section -->
    <div class="section basic-info">
      <h3 class="section-title">基本信息</h3>
      <div class="form-row">
        <div class="form-group">
          <label for="EarSignal">耳号 <span class="required">*</span></label>
          <input 
            type="text" 
            id="EarSignal" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.EarSignal }"
            v-model="formData.EarSignal"
            @blur="validateField('EarSignal')"
            placeholder="请输入耳号">
          <div v-if="validationErrors.EarSignal" class="invalid-feedback">耳号为必填项</div>
        </div>
        <div class="form-group">
          <label for="Variety">品种 <span class="required">*</span></label>
          <select 
            id="Variety" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.Variety }"
            v-model="formData.Variety"
            @change="validateField('Variety')">
            <option value="">请选择品种</option>
            <option value="1">荷斯坦牛</option>
            <option value="2">娟姗牛</option>
            <option value="3">西门塔尔牛</option>
            <option value="4">安格斯牛</option>
          </select>
          <div v-if="validationErrors.Variety" class="invalid-feedback">品种为必填项</div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="ElectronicEarTag">电子耳标号 <span class="required">*</span></label>
          <input 
            type="text" 
            id="ElectronicEarTag" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.ElectronicEarTag }"
            v-model="formData.ElectronicEarTag"
            @blur="validateField('ElectronicEarTag')"
            placeholder="请输入电子耳标号">
          <div v-if="validationErrors.ElectronicEarTag" class="invalid-feedback">电子耳标号为必填项</div>
        </div>
        <div class="form-group">
          <label for="GeneRank">基因等级 <span class="required">*</span></label>
          <select 
            id="GeneRank" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.GeneRank }"
            v-model="formData.GeneRank"
            @change="validateField('GeneRank')">
            <option value="">请选择基因等级</option>
            <option value="1">A级</option>
            <option value="2">B级</option>
            <option value="3">C级</option>
            <option value="4">D级</option>
          </select>
          <div v-if="validationErrors.GeneRank" class="invalid-feedback">基因等级为必填项</div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="Gender">性别 <span class="required">*</span></label>
          <select 
            id="Gender" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.Gender }"
            v-model="formData.Gender"
            @change="validateField('Gender')">
            <option value="">请选择性别</option>
            <option v-for="option in genderOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <div v-if="validationErrors.Gender" class="invalid-feedback">性别为必填项</div>
        </div>
        <div class="form-group">
          <label for="BirthStatus">出生状态 <span class="required">*</span></label>
          <select 
            id="BirthStatus" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.BirthStatus }"
            v-model="formData.BirthStatus"
            @change="validateField('BirthStatus')">
            <option value="">请选择出生状态</option>
            <option v-for="option in birthStatusOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <div v-if="validationErrors.BirthStatus" class="invalid-feedback">出生状态为必填项</div>
        </div>
      </div>
    </div>

    <!-- Birth Information Section -->
    <div class="section birth-info">
      <h3 class="section-title">出生信息</h3>
      <div class="form-row">
        <div class="form-group">
          <label for="FatherNumber">父耳号 <span class="required">*</span></label>
          <select 
            id="FatherNumber" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.FatherNumber }"
            v-model="formData.FatherNumber"
            @change="validateField('FatherNumber')">
            <option value="">请选择父耳号</option>
            <option v-for="option in fatherNumberOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <div v-if="validationErrors.FatherNumber" class="invalid-feedback">父耳号为必填项</div>
        </div>
        <div class="form-group">
          <label for="MotherNumber">母耳号 <span class="required">*</span></label>
          <select 
            id="MotherNumber" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.MotherNumber }"
            v-model="formData.MotherNumber"
            @change="validateField('MotherNumber')">
            <option value="">请选择母耳号</option>
            <option v-for="option in motherNumberOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <div v-if="validationErrors.MotherNumber" class="invalid-feedback">母耳号为必填项</div>
        </div>
        <div class="form-group">
          <label for="DateofBirth">出生日期 <span class="required">*</span></label>
          <input 
            type="date" 
            id="DateofBirth" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.DateofBirth }"
            v-model="formData.DateofBirth"
            @change="validateField('DateofBirth')">
          <div v-if="validationErrors.DateofBirth" class="invalid-feedback">出生日期为必填项</div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="EntryDate">入场日期 <span class="required">*</span></label>
          <input 
            type="date" 
            id="EntryDate" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.EntryDate }"
            v-model="formData.EntryDate"
            @change="validateField('EntryDate')">
          <div v-if="validationErrors.EntryDate" class="invalid-feedback">入场日期为必填项</div>
        </div>
        <div class="form-group">
          <label for="PlaceOfBirth">出生场地 <span class="required">*</span></label>
          <select 
            id="PlaceOfBirth" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.PlaceOfBirth }"
            v-model="formData.PlaceOfBirth"
            @change="validateField('PlaceOfBirth')">
            <option value="">请选择出生场地</option>
            <option v-for="option in placeOfBirthOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <div v-if="validationErrors.PlaceOfBirth" class="invalid-feedback">出生场地为必填项</div>
        </div>
        <div class="form-group">
          <label for="BirthWeight">出生重量 <span class="required">*</span></label>
          <input 
            type="number" 
            id="BirthWeight" 
            class="form-control" 
            :class="{ 'is-invalid': validationErrors.BirthWeight }"
            v-model.number="formData.BirthWeight"
            @blur="validateField('BirthWeight')"
            placeholder="请输入出生重量(kg)" 
            min="0"
            step="1">
          <div v-if="validationErrors.BirthWeight" class="invalid-feedback">出生重量为必填项</div>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group full-width">
          <label for="Note">备注</label>
          <textarea 
            id="Note" 
            class="form-control" 
            v-model="formData.Note"
            rows="4" 
            placeholder="请输入备注信息"></textarea>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.livestock-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* Action Buttons */
.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

/* Validation styles */
.required {
  color: #dc3545;
  font-weight: bold;
}

.is-invalid {
  border-color: #dc3545 !important;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

.invalid-feedback {
  display: block;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875rem;
  color: #dc3545;
  font-weight: 500;
}

.btn-red {
  background-color: #dc3545;
  color: white;
}

.btn-red:hover {
  background-color: #c82333;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3);
}

.btn-icon {
  width: 18px;
  height: 18px;
}

/* Sections */
.section {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 25px;
}

.section-title {
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e9ecef;
}

.basic-info {
  margin-bottom: 30px;
}

.birth-info {
  margin-top: 30px;
}

/* Form Layout */
.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 500;
  color: #495057;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-control {
  padding: 12px 15px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  background-color: #fff;
}

.form-control:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-control::placeholder {
  color: #6c757d;
  font-size: 13px;
}

textarea.form-control {
  resize: vertical;
  min-height: 100px;
}

/* Responsive Design */
@media (max-width: 768px) {
  .action-buttons {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .btn {
    padding: 10px 16px;
    font-size: 13px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .section {
    padding: 20px;
  }
}

@media (max-width: 480px) {
  .livestock-management {
    padding: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .btn {
    justify-content: center;
  }
}
</style>
